package com.ihighest.app.infox.fragment;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.QuestionContentActivity;
import com.ihighest.app.infox.adapter.NewListViewAdapter;
import com.ihighest.app.infox.tools.CheckNetWork;

public class Nj_Fragment_Waitforyou extends Fragment {

	final static String TAG = "Nj_Fragment_Waitforyou";
 
	View view;
	private final Context context;
	private PullToRefreshListView listview;
	private NewListViewAdapter waitlistviewadapter;
	String location = "0:0:0";
	JSONArray jsonArray;
	int page = 1;
	long longtime = 0;

	private TextView emptyview;

	private ReflashBroadcast reflashBroadcast;

	public Nj_Fragment_Waitforyou(Context context) {
		super();
		this.context = context;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.infox_agriculturaltechnology_waitpager, null);
		listview = (PullToRefreshListView) view.findViewById(R.id.id_wait_listview);
		jsonArray = new JSONArray();
		waitlistviewadapter = new NewListViewAdapter(context, jsonArray);
		listview.setAdapter(waitlistviewadapter);

		emptyview = new TextView(context);
		emptyview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		emptyview.setText("加载中...");
		emptyview.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		emptyview.setVisibility(View.GONE);
		listview.setEmptyView(emptyview);

//		reflashBroadcast = new ReflashBroadcast();
//		IntentFilter filter = new IntentFilter();
//		filter.addAction(Const.REFLASH);
//		context.registerReceiver(reflashBroadcast, filter);

		try {
			location = SharedPreferencesKit.getJsonObject(context, Const.SP_KEY_BD_LOCAITON).getString("loc");
		} catch (JSONException ex) {
			Log.e(TAG, ex.getMessage(), ex);
		}
		getdata();
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				arg2 = arg2 - 1;
				Intent intent = new Intent(context, QuestionContentActivity.class);
				Bundle bundle = new Bundle();
				try {
					bundle.putString("id", jsonArray.getJSONObject(arg2).getString("id"));
				} catch (JSONException e) {
					Log.e(TAG, e.getMessage(), e);
				}
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		listview.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {

				if (CheckNetWork.isConnected(context)) {
					emptyview.setText("加载中...");
					page = 1;
					longtime = 0;
					getdata();
				} else {
					ToastKit.showShort(context, "请连接网络");
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {

				if (CheckNetWork.isConnected(context)) {

					page++;
					getdata();

				} else {
					ToastKit.showShort(context, "请连接网络");
				}
			}
		});

		return view;
	}

	private void getdata() {
		System.err.println("进入 " + TAG + " 时间：" + System.currentTimeMillis());
		ApiParam param = ApiParam.create().addParam("type", "wait").addParam("page", page).addParam("location", location);
		if (longtime != 0) {
			param.addParam("time", longtime);
		}
		Api.get("qa/list", param, new ApiCallback(context, true) {

			@Override
			public void handleSuccess(ApiResult result) {

				if (result.getCode() == 100) {
					longtime = result.getTime();
					if (page == 1) {

						if (result.getDatas() == null || result.getDatas().length() <= 0) {

							emptyview.setText("问题列表为空");
						}

						SharedPreferencesKit.putJsonArray(context, Const.NJ_WAIT_JSONARRAY_CACHE, result.getDatas());
						jsonArray = result.getDatas();
						waitlistviewadapter.setData(result.getDatas());
					} else {
						try {
							if (result.getDatas() == null || result.getDatas().length() <= 0) {
								page--;
							} else {
								jsonArray = AppKit.joinJSONArray(jsonArray, result.getDatas());
								waitlistviewadapter.appendData(result.getDatas());
							}
						} catch (JSONException e) {
							Log.e(TAG, e.getMessage(), e);
						}
					}
				} else {
					emptyview.setText("加载失败，请稍后刷新");
				}
				listview.onRefreshComplete();
			}

			@Override
			public void handleFailure(Exception e, String msg) {
				listview.onRefreshComplete();
				emptyview.setText("加载失败，请稍后刷新");
			}
		}, context);

	}

	public class ReflashBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 得到数据变化的广播
			if (intent.getAction().equals(Const.REFLASH)) {
				page = 1;
				longtime = 0;
				getdata();

			}

		}

	}

}
